<template>
  <div class="login">
    <!-- navBar虽然书写时在Login页面中 => 渲染时传递到了.appHeader -->
    <teleport to=".app-header">
      <van-nav-bar
        title="登录"
        left-text="返回"
        left-arrow
        @click-left="back"
      ></van-nav-bar>
    </teleport>
    <van-form ref="formLogin" autocomplete="off" class="register-form" @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="info.loginname"
          name="tel"
          label="手机号"
          placeholder="手机号"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <van-field
          v-model="info.password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 提交 </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { doUserLoginAPI } from "@/api/user.js";
import { showSuccessToast, showFailToast } from "vant";
import { useRoute, useRouter } from "vue-router";
import { useUserStore } from "@/stores/user.js";

let route = useRoute();
let router = useRouter();
let store = useUserStore();

let info = reactive({
  loginname: "",
  password: "",
});
let formLogin = ref();

let onSubmit = async () => {
  // var res = formLogin.value.getValidationStatus()
  var { loginname, password } = info;
  if (loginname && password) {
    console.log("准备登录");

    try {
      var result = await doUserLoginAPI(info);
      console.log(result);
      showSuccessToast("登录成功");
      store.UpdateAuthorityState(result.data);

      let query = route.query;
      console.log(query);
      if (query.ReturnUrl) {
        // router.back();

        let path = decodeURIComponent(query.ReturnUrl);
        router.replace(path);
      } else {
        router.push("/home");
      }

      return true;
    } catch (err) {
      showFailToast(err.message);
      return false;
    }
  }
};
</script>

<style lang="scss" scoped></style>
